<template>
  <div class="products-container">
    <el-row :gutter="20">
      <el-col :span="24">
        <div class="toolbar">
          <el-input
            v-model="searchQuery"
            placeholder="搜索商品"
            prefix-icon="Search"
            clearable
            class="search-input"
          />
          <el-space>
            <el-select v-model="category" placeholder="商品分类" clearable>
              <el-option
                v-for="item in categories"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
            <el-select v-model="sortBy" placeholder="排序方式">
              <el-option label="默认排序" value="" />
              <el-option label="价格从低到高" value="priceAsc" />
              <el-option label="价格从高到低" value="priceDesc" />
              <el-option label="销量优先" value="sales" />
            </el-select>
          </el-space>
        </div>
      </el-col>
    </el-row>

    <el-row :gutter="20">
      <el-col 
        v-for="product in filteredProducts" 
        :key="product._id"
        :xs="24"
        :sm="12"
        :md="8"
        :lg="6"
        :xl="6"
      >
        <el-card class="product-card" :body-style="{ padding: '0px' }">
          <div class="product-image">
            <el-image
              :src="product.images[0]"
              fit="cover"
              loading="lazy"
              :preview-src-list="product.images"
            >
              <template #error>
                <div class="image-placeholder">
                  <el-icon><Picture /></el-icon>
                </div>
              </template>
            </el-image>
            <div v-if="product.discount > 0" class="discount-badge">
              {{ product.discount }}% OFF
            </div>
          </div>
          <div class="product-content">
            <h3 class="product-title" :title="product.name">{{ product.name }}</h3>
            <p class="product-desc">{{ product.description }}</p>
            <div class="product-price">
              <template v-if="product.discount > 0">
                <span class="current-price">
                  ¥{{ ((product.price * (100 - product.discount)) / 100).toFixed(2) }}
                </span>
                <span class="original-price">¥{{ product.price.toFixed(2) }}</span>
              </template>
              <template v-else>
                <span class="current-price">¥{{ product.price.toFixed(2) }}</span>
              </template>
            </div>
            <div class="product-footer">
              <el-button 
                type="primary" 
                :icon="ShoppingCart"
                @click="addToCart(product)"
              >
                加入购物车
              </el-button>
              <el-button 
                :icon="InfoFilled"
                @click="viewDetail(product._id)"
              >
                查看详情
              </el-button>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-empty v-if="filteredProducts.length === 0" description="暂无商品" />
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Search, Picture, ShoppingCart, InfoFilled } from '@element-plus/icons-vue'
import { useCartStore } from '@/stores/cart'
import type { Product } from '@/types'

const router = useRouter()
const cartStore = useCartStore()

// 模拟数据
const mockProducts: Product[] = [
  {
    _id: '1',
    name: 'iPhone 15 Pro',
    description: '超强性能，专业摄影，尽在iPhone 15 Pro',
    price: 8999,
    stock: 100,
    category: 'phones',
    images: ['https://picsum.photos/400/400'],
    status: 'active',
    discount: 5,
    createdAt: new Date().toISOString(),
    updatedAt: new Date().toISOString()
  },
  {
    _id: '2',
    name: 'MacBook Pro 14"',
    description: 'M3 Pro芯片，创作无界',
    price: 14999,
    stock: 50,
    category: 'computers',
    images: ['https://picsum.photos/400/400'],
    status: 'active',
    discount: 0,
    createdAt: new Date().toISOString(),
    updatedAt: new Date().toISOString()
  },
  {
    _id: '3',
    name: 'iPad Air',
    description: '轻盈强大，随时创造',
    price: 4799,
    stock: 200,
    category: 'tablets',
    images: ['https://picsum.photos/400/400'],
    status: 'active',
    discount: 10,
    createdAt: new Date().toISOString(),
    updatedAt: new Date().toISOString()
  },
  {
    _id: '4',
    name: 'AirPods Pro',
    description: '主动降噪，沉浸音质',
    price: 1999,
    stock: 300,
    category: 'accessories',
    images: ['https://picsum.photos/400/400'],
    status: 'active',
    discount: 15,
    createdAt: new Date().toISOString(),
    updatedAt: new Date().toISOString()
  }
]

const categories = [
  { label: '手机', value: 'phones' },
  { label: '电脑', value: 'computers' },
  { label: '平板', value: 'tablets' },
  { label: '配件', value: 'accessories' }
]

const searchQuery = ref('')
const category = ref('')
const sortBy = ref('')

const filteredProducts = computed(() => {
  let result = [...mockProducts]

  // 搜索过滤
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    result = result.filter(product => 
      product.name.toLowerCase().includes(query) || 
      product.description.toLowerCase().includes(query)
    )
  }

  // 分类过滤
  if (category.value) {
    result = result.filter(product => product.category === category.value)
  }

  // 排序
  switch (sortBy.value) {
    case 'priceAsc':
      result.sort((a, b) => a.price - b.price)
      break
    case 'priceDesc':
      result.sort((a, b) => b.price - a.price)
      break
    case 'sales':
      // 这里应该根据实际销量排序，现在只是示例
      result.sort(() => Math.random() - 0.5)
      break
  }

  return result
})

const addToCart = async (product: Product) => {
  try {
    await cartStore.addToCart(product._id, 1)
    ElMessage.success('已添加到购物车')
  } catch (error) {
    ElMessage.error('添加失败，请重试')
  }
}

const viewDetail = (productId: string) => {
  router.push(`/mall/product/${productId}`)
}
</script>

<style scoped>
.products-container {
  padding: 20px 0;
}

.toolbar {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 20px;
}

.search-input {
  max-width: 300px;
}

.product-card {
  margin-bottom: 20px;
  transition: all 0.3s ease;
}

.product-card:hover {
  transform: translateY(-5px);
  box-shadow: var(--el-box-shadow-light);
}

.product-image {
  position: relative;
  height: 200px;
  overflow: hidden;
}

.product-image .el-image {
  width: 100%;
  height: 100%;
}

.image-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: var(--el-fill-color-light);
  color: var(--el-text-color-secondary);
}

.image-placeholder .el-icon {
  font-size: 48px;
}

.discount-badge {
  position: absolute;
  top: 10px;
  right: 10px;
  background: var(--el-color-danger);
  color: white;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: bold;
}

.product-content {
  padding: 14px;
}

.product-title {
  margin: 0;
  font-size: 16px;
  font-weight: 500;
  color: var(--el-text-color-primary);
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.product-desc {
  margin: 8px 0;
  font-size: 14px;
  color: var(--el-text-color-secondary);
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  height: 40px;
}

.product-price {
  margin: 12px 0;
}

.current-price {
  font-size: 20px;
  font-weight: bold;
  color: var(--el-color-danger);
}

.original-price {
  margin-left: 8px;
  font-size: 14px;
  color: var(--el-text-color-secondary);
  text-decoration: line-through;
}

.product-footer {
  display: flex;
  gap: 10px;
  margin-top: 12px;
}

.product-footer .el-button {
  flex: 1;
}

@media (max-width: 768px) {
  .toolbar {
    flex-direction: column;
    align-items: stretch;
  }

  .search-input {
    max-width: none;
  }

  .product-image {
    height: 160px;
  }
}
</style> 